package dbTools

import (
	"fmt"
	_ "github.com/godror/godror"
	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlserver"
	"gorm.io/gorm"
	"vueProject/globalData"
	"vueProject/models/sys_db"
)

// 组返回信息格式
func returnMsg(code int, msg string) interface{} {
	return map[string]interface{}{
		"code": code,
		"msg":  msg,
	}
}

// ConnectSdb 连接服务数据库
func ConnectSdb(dbID int64) interface{} {
	//if (dbConf == controller.DbConnect{}) {
	//	//return "", errors.New("请正确输入链接字符串内容！")
	//	return returnMsg(-1, "请正确输入链接字符串内容！")
	//}
	//kessel:kessel@tcp(localhost)/data?charset=utf8&parseTime=True&loc=Local
	//123456:123456@tcp(localhost)/lypeis?charset=utf8&parseTime=True&loc=Local
	var DbconnectData sys_db.DbConnectList

	globalData.LocalDb.Where("id = ?", dbID).Find(&DbconnectData)
	if DbconnectData.Type == "Oracle" {
		connectStr := fmt.Sprintf("%v/%v@%v:%v/%v", DbconnectData.Username, DbconnectData.Password, DbconnectData.Address, DbconnectData.Port, DbconnectData.Database)
		globalData.ServerDb, err = gorm.Open(sqlserver.Open(connectStr), &gorm.Config{})
	} else if DbconnectData.Type == "MySQL" {
		connectStr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", DbconnectData.Username, DbconnectData.Password, DbconnectData.Address, DbconnectData.Port, DbconnectData.Database)
		globalData.ServerDb, err = gorm.Open(mysql.Open(connectStr), &gorm.Config{})
	}

	if err != nil {
		globalData.ServerDb = nil
		return returnMsg(-1, err.Error())
	}
	//return returnMsg(200, DbconnectData.Remarks)
	return returnMsg(200, "连接成功")
}

func CloseSdb() interface{} {
	closeDB, _ := globalData.ServerDb.DB()
	//if SdbErr != nil {
	//	return map[string]interface{}{
	//		"code": -1,
	//		"msg":  SdbErr.Error(),
	//	}
	//}
	closeErr := closeDB.Close()
	if closeErr != nil {
		return map[string]interface{}{
			"code": -1,
			"msg":  closeErr.Error(),
		}
	}
	return map[string]interface{}{
		"code": 200,
		"msg":  "关闭连接成功",
	}
}
